package com.wq.service.impl;


import com.alibaba.fastjson2.JSON;
import com.qiniu.http.Response;
import com.qiniu.storage.Configuration;
import com.qiniu.storage.DownloadUrl;
import com.qiniu.storage.Region;
import com.qiniu.storage.UploadManager;
import com.qiniu.storage.model.DefaultPutRet;
import com.qiniu.util.Auth;
import com.wq.config.QiniuConfig;
import com.wq.service.FileService;
import com.wq.vo.FileUploadVO;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import java.io.InputStream;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.UUID;

@Slf4j
@Service

public class FileServiceImpl implements FileService {


    @Resource
    private QiniuConfig qiniuConfig;
    @Override
    public FileUploadVO upload(MultipartFile file) {
        FileUploadVO fileUploadVO = new FileUploadVO();
        try {
            //1.获取凭证
            Auth auth = Auth.create(qiniuConfig.getAccessKey(), qiniuConfig.getSecretKey());
            //2.获取上传凭证
            String upToken = auth.uploadToken(qiniuConfig.getBucket());
            //4.配置所在区域
            Configuration cfg = new Configuration(Region.autoRegion());
            //3.上传管理工具
            UploadManager uploadManager = new UploadManager(cfg);
            //5.补全参数
            InputStream inputStream = file.getInputStream();
            //获取file地址
            String originalFilename = file.getOriginalFilename();
            //file扩展名
            String extendFileName = originalFilename.substring(originalFilename.lastIndexOf("."));
            LocalDate currentDate=LocalDate.now();
            DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy/MM/dd");
            String newFileName=currentDate.format(formatter)+ UUID.randomUUID().toString().replace("-","")+extendFileName;
            log.info("newFileName:{}",newFileName);
            //6.上传
            Response res = uploadManager.put(inputStream, newFileName, upToken, null, null);
         //   DefaultPutRet defaultPutRet = JSON.parseObject(res.bodyString(), DefaultPutRet.class);
            DownloadUrl downloadUrl = new DownloadUrl(qiniuConfig.getPrefixUrl(),false,newFileName);

            //过期的时间戳 格林威治时间1970年1月1日0时0分0秒0毫秒到当前时间的毫秒值就叫时间戳
            long deadline = System.currentTimeMillis() + 3600000L;

            auth = Auth.create(qiniuConfig.getAccessKey(), qiniuConfig.getSecretKey());
            String urlStr = downloadUrl.buildURL(auth, deadline);
            fileUploadVO.setUrl(urlStr);
        }catch (Exception e){
            e.printStackTrace();
        }

        return fileUploadVO;
    }
}
